package com.mijie.homi.api;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mijie.core.ApplicationProperties;
import com.mijie.core.Status;
import com.mijie.homi.common.constant.HomiStatusCode;
import com.mijie.homi.common.domain.Upgrade;
import com.mijie.homi.common.domain.user.User;
import com.mijie.homi.domain.commom.EmailVerify;
import com.mijie.homi.domain.commom.ResetPassword;
import com.mijie.homi.service.common.MixService;
import com.mijie.homi.service.user.UserService;
import com.mijie.homi.util.ServerHelper;
import com.mijie.util.DateUtil;
import com.mijie.util.Helper;
import com.mijie.util.IOUtil;

@Controller
@RequestMapping("/sys")
public class SysApi {

	@Autowired
	private MixService mixService;
	@Autowired
	private UserService userService;
	
	private Logger logger = Logger.getLogger(SysApi.class);
	
	
	@RequestMapping(value="/protocol",method=RequestMethod.GET)
	public @ResponseBody void protocol(HttpServletRequest request,HttpServletResponse response) {
		Status status = new Status(request,response);
		status.setResult("{\"link\":\""+ApplicationProperties.get("homi.protocol.url")+"\"}");
		status.write();
	}
	
	@RequestMapping(value="/email/verify/apply",method=RequestMethod.GET)
	public @ResponseBody void emailVerifyApply(HttpServletRequest request,HttpServletResponse response) {
		Integer userId = ServerHelper.getUserId(request);
		User user = userService.getUserById(userId);
		Status status = new Status(request,response);
		userService.sendMailForVerify(user);
		status.write();
	}
	
	@RequestMapping(value="/password/reset/apply",method=RequestMethod.GET)
	public @ResponseBody void passwordResetApply(String email,HttpServletRequest request,HttpServletResponse response){
		User user = userService.getUserByEmail(email);
		Status status = new Status(request,response);
		if(user!=null){
			userService.sendMailForResetPassword(user);
		}else{
			status.setCode(HomiStatusCode.USER_NOT_FOUND);
		}
		status.write();
	}
	
	@RequestMapping(value="/email/verify",method=RequestMethod.GET)
	public String emailVerify(String code,
			HttpServletRequest request,HttpServletResponse response,Model model) {
		
			EmailVerify verify = mixService.getEmailVerifyApply(code);
			
			String message = "无效链接";
			if(verify!=null){
				if(DateUtil.getMinuteInterval(verify.getCreateAt(), new Date())<=60*48){
					String[] entry = code.split("\\.");
					if(entry!=null && entry.length==2){
						if(entry[0].length()==32 && Helper.isInt(entry[1])){
							if(userService.emailVerifyPass(Integer.parseInt(entry[1]),code)>0){
								message = "验证成功。";
							}else{
								mixService.deleteEmailVerifyApply(code);
								message = "oh!出了点小意外，请重新申请验证。";
							}
						}
					}
				}else{
					mixService.deleteEmailVerifyApply(code);
					message = "链接已经失效，请重启申请验证。";
				}
			}else{
				message = "请求不存在,请重新申请验证。";
			}
			logger.info("emailVerify code:"+code+",find request ? "+(verify!=null));
			model.addAttribute("message", message);
		return "/emailVerify";
	}
	
	@RequestMapping(value="/password/reset",method=RequestMethod.GET)
	public String passwordReset(String code,HttpServletRequest request,Model model) throws IOException{
		boolean alreadReset = false;
		Cookie[] cookies = request.getCookies();
		if(cookies!=null){
			for(Cookie c : cookies){
				if(c.getName().equals(code)){
					alreadReset = true;
					break;
				}
			}
		}
		
		if(!alreadReset){
			ResetPassword reset = mixService.getResetPasswordApply(code);
			if(reset!= null && DateUtil.getMinuteInterval(reset.getCreateAt(), new Date())<=60*48){
				model.addAttribute("timeout", false);
				model.addAttribute("code", code);
			}else{
				model.addAttribute("timeout", true);
			}
		}else{
			model.addAttribute("message", "您已点击过此链接并进行操作过，如需再次重置密码请到应用那里再次点击找回密码功能。");
		}
		return "/resetpasswd";
	}
	
	@RequestMapping(value="/password/save",method=RequestMethod.POST)
	public String passwordSave(String code,String newpasswd,String confirmpasswd,
			HttpServletRequest request,HttpServletResponse response,Model model) throws IOException {
		boolean alreadReset = false;
		Cookie[] cookies = request.getCookies();
		if(cookies!=null){
			for(Cookie c : cookies){
				if(c.getName().equals(code)){
					alreadReset = true;
					break;
				}
			}
		}
		if(!alreadReset){
			ResetPassword reset = mixService.getResetPasswordApply(code);
			if(reset!=null && DateUtil.getMinuteInterval(reset.getCreateAt(), new Date())<=60*48){
				if(newpasswd==null  || confirmpasswd==null){
					model.addAttribute("message", "请输入新密码");
				}else if(!newpasswd.equals(confirmpasswd)){
					model.addAttribute("message", "两次密码不相同");
				}else{
					User user = userService.getUserById(reset.getUserId());
					model.addAttribute("message", "无效链接");
					if(user!=null){
						int rows = userService.resetPasswdByWeb(user.getId(), newpasswd,code);
						if(rows>0) {
							model.addAttribute("message", "密码重置成功");
						}else{
							model.addAttribute("message", "oh!出了点小意外，请重新申请密码重置。");
						}
						Cookie cookie = new Cookie(code,"true");
						cookie.setMaxAge(60*60*48);
						response.addCookie(cookie);
					}
				}
			}else{
				model.addAttribute("message", "链接已经失效");
			}
		}else{
			model.addAttribute("message", "您已点击过此链接并进行操作过，如需再次重置密码请到应用那里再次点击找回密码功能。");
		}
		return "/message";
	}
}
